using Aurora.TaskScheduler.Abstractions;
using Aurora.TaskScheduler.DistributedLock.NewLifeRedis;

namespace Aurora.TaskScheduler.DistributedLock;

/// <summary>
/// redis task 分布式锁
/// </summary>
public class RedisTaskDistributeLock : ITaskDistributeLock
{
    private readonly NewLifeRedisCache _redis;

    public RedisTaskDistributeLock(NewLifeRedisCache redis)
    {
        _redis = redis;
    }
    /// <summary>
    /// 
    /// </summary>
    /// <param name="taskId"></param>
    /// <param name="timeout"></param>
    /// <returns></returns>
    public Task<bool> TryLockAsync(string taskId, TimeSpan timeout)
    {
        string lockKey = "TASK-JOB-LOCK:" + taskId;
        return Task.FromResult(_redis.AcquireLock(lockKey, timeout.TotalMicroseconds.ToInt()));
    }
    /// <summary>
    /// 
    /// </summary>
    /// <param name="taskId"></param>
    /// <returns></returns>
    public Task<bool> TryUnlockAsync(string taskId)
    {
        string lockKey = "TASK-JOB-LOCK:" + taskId;
        _redis.Del(lockKey);
        return Task.FromResult(true);
    }
}